﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebClasses.Pages;
using DomainModel;

public partial class Admin_CategoryManage : NormalPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindingData();

            if (!string.IsNullOrEmpty(Request["ID"]))
            {
                ChangeToUpdateStatus();
            }
        }

    }

    private void BindingData()
    {
        IEnumerable<Category> categoryList = this.LogicController.ProductManager.GetAllCategories();
        rptCategoryList.DataSource = categoryList.Where(c => c.ID != 1);
        rptCategoryList.DataBind();


        categoryList = categoryList.Where(c => c.ID == 1 || c.ParentID == 1);
        ddlParentList.Items.Clear();
        foreach (Category cate in categoryList)
        {
            ddlParentList.Items.Add(new ListItem(cate.CategoryName, cate.ID.ToString()));
        }
    }

    private void ChangeToUpdateStatus()
    {
        btnCreate.Visible = false;
        btnUpdate.Visible = true;
        int id = 0;
        int.TryParse(Request["ID"], out id);

        Category cate = this.LogicController.ProductManager.GetCategoryByID(id);

        txtName.Text = cate.CategoryName;
        txtRank.Text = cate.Rank.ToString();
        ddlParentList.Items.FindByValue(cate.ParentID.ToString()).Selected = true;
    }

    protected void btnCreate_Click(object sender, EventArgs e)
    {
        this.LogicController.ProductManager.CreateNewCategory(new Category
        {
            CategoryName = txtName.Text,
            Rank = int.Parse(txtRank.Text),
            ParentID = int.Parse(ddlParentList.SelectedValue),
        });

        BindingData();
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        int id = 0;
        int.TryParse(Request["ID"], out id);

        Category cate = this.LogicController.ProductManager.GetCategoryByID(id);
        cate.CategoryName = txtName.Text;
        cate.Rank = int.Parse(txtRank.Text);
        cate.ParentID = int.Parse(ddlParentList.SelectedValue);

        this.LogicController.ProductManager.UpdateCategory(cate);
        BindingData();
        btnCreate.Visible = true;
        btnUpdate.Visible = false;
        txtName.Text = string.Empty;
        txtRank.Text = string.Empty;
    }

    protected void rptCategoryList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "del")
        {
            this.LogicController.ProductManager.DeleteCategoryByID(Convert.ToInt32(e.CommandArgument));

            BindingData();
        }
    }
}
